package com.controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dto.Signature;
import com.service.MsgService;
import com.weixin.service.WeiXinService;

@Controller
@RequestMapping("/weixin")
public class WeiXinController {
    private final static Logger _log = Logger.getLogger(WeiXinController.class);
    private final static String MSGNULL = "";
    private SAXReader reader = new SAXReader();

    public WeiXinController() {
	// TODO Auto-generated constructor stub
	_log.info(this + "     init");
    }

    private List<String> list = new ArrayList<String>();

    @Resource
    private MsgService msgService;
    @Resource
    private WeiXinService weiXinService;

    /**
     * 微信主要入口
     * 
     * @param xml
     * @param request
     * @return
     * @throws DocumentException 
     */
    @RequestMapping(value = "api.do", method = RequestMethod.POST)
    @ResponseBody
    public Object api(InputStream stream) throws DocumentException {
	Document document = reader.read(stream);
	Element root = document.getRootElement();
	List<Element> elementList = root.elements();
	Map<String, String> msg=new HashMap<String, String>();
	for (Element element : elementList) {
	    msg.put(element.getName(), element.getText());
	}
	if (list.size() > 30) {
	    list.clear();
	}
	list.add(document.asXML());
	Object out = msgService.onMsgReveived(msg);
	System.out.println(out);
	return out == null ? MSGNULL : out;
    }

    @RequestMapping("show.do")
    public String Show(Model model) {
	model.addAttribute("list", list);
	return "show.jsp";
    }

    /**
     * 消息真实性校验
     * 
     * @param signature
     * @return
     */
    @RequestMapping(value = "api.do", method = RequestMethod.GET)
    public void Signature(Signature signature, Writer writer) {
	if (list.size() > 30) {
	    list.clear();
	}
	list.add(signature.getSignature());
	if (weiXinService.ChackSignature(signature)) {
	    try {
		writer.write(signature.getEchostr());
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
    }

}
